from fastapi import APIRouter,Path,Query, Cookie, Header
from typing import Optional, List
from .models import CityInfo, CityName, CityInfo2, Data


shop = APIRouter()

@shop.get("/city/{city}")
async def shop_food(city:str, query_string:Optional[str]= None):

    return {"food":"food", "city":city, "query_string":query_string}


@shop.post("/AddCity/{city}")
async def result(city: str, city_info: CityInfo):

    return {"city": city, "country": city_info.country, "is_affected": city_info.is_affected}

# 选择性的参数
@shop.get("/enum/{city}")
async def latest(city: CityName):
    if city == CityName.Shanghai:
        return 123
    return 345

# 传递路径
@shop.get("/files/{file_path:path}")
async def filepath(file_path: str):

    return f"path {file_path}"

# 校验路径参数
@shop.get("/path/{num}")
async def path_params_validate(
    num: int = Path(...,title="number", description="不可描述", ge=1, le=10)
):
    return num

@shop.get("/query")
async def page_limit(page: int=1,limit: Optional[int] = None ):
    if limit:
        return {"page": page, "limit":limit}
    return {"page": page}


@shop.get("/query/bool/conversion")
async def type_conversion(param: bool=False):

    return param

# 校验查询参数
@shop.get("/query/validations")
async def query_params_validate(
    value: str = Query(...,title="number", description="不可描述", min_length=8,
                       max_length=16, regex="^a"),
    data: List[str] = Query(default=["v1", "v2"], alias="别名")
):
    return value,data

# 请求体的请求
@shop.get("/request_body/city")
async def city_info_2(city: CityInfo2):

    return city.name


# 且套的请求
@shop.post("/request_body/nested")
async def nested_models(data: Data):

    return data

# cookie header
@shop.get("/cookie")
async def cookie(cookie_id: Optional[str] = Cookie(None)):

    return {"cookie_id": cookie_id}

@shop.get("/header")
async def header(user_agent: Optional[str] = Header(None, convert_underscores=True),
                 x_token: List[str]= Header(None)):
    """
    有些http代理和服务器是不允许请求头中带有下划线的，所以
    :param user_agent: convert_underscores=True 会把user_agent 变为user-agent
    :param x_token:
    :return:
    """
    return {"user_agent": user_agent, "x_token":x_token}